<template>
  <div class="game-canvas-container">
    <div class="canvas-toolbar">
      <div class="color-picker">
        <label>选择颜色:</label>
        <input 
          type="color" 
          v-model="currentColor" 
          @change="updateBrushColor"
          class="color-input"
          :disabled="!isGameActive"
        />
      </div>
      <div class="brush-size">
        <label>画笔大小:</label>
        <input 
          type="range" 
          min="1" 
          max="20" 
          v-model="brushSize" 
          @input="updateBrushSize"
          class="brush-slider"
          :disabled="!isGameActive"
        />
        <span>{{ brushSize }}px</span>
      </div>
      <div class="tool-buttons">
        <button 
          @click="clearCanvas" 
          class="tool-btn clear-btn"
          :disabled="!isGameActive"
          title="清空画布"
        >
          🗑️ 清空
        </button>
        <button 
          @click="undo" 
          class="tool-btn undo-btn"
          :disabled="!canUndo || !isGameActive"
          title="撤销"
        >
          ↩️ 撤销
        </button>
      </div>
    </div>
    
    <div class="canvas-wrapper">
      <canvas
        ref="canvasRef"
        @mousedown="startDrawing"
        @mousemove="draw"
        @mouseup="stopDrawing"
        @mouseleave="stopDrawing"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
        class="game-canvas"
        :width="canvasWidth"
        :height="canvasHeight"
      ></canvas>
      
      <div class="canvas-overlay" v-if="!isGameActive">
        <div class="overlay-content">
          <h3 v-if="gameStatus === 'waiting'">等待游戏开始...</h3>
          <h3 v-else-if="gameStatus === 'finished'">游戏结束</h3>
          <p v-if="gameStatus === 'waiting'">请等待其他玩家加入</p>
        </div>
      </div>
    </div>
    
    <div class="game-info">
      <div class="player-info">
        <span class="player-color" :style="{ backgroundColor: currentColor }"></span>
        <span>你的颜色: {{ currentColor }}</span>
      </div>
      <div class="game-status">
        <span v-if="gameTime > 0 && gameStatus === 'playing'">剩余时间: {{ formatTime(gameTime) }}</span>
        <span v-else-if="gameStatus === 'finished'">游戏结束</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'

const props = defineProps({
  isGameActive: {
    type: Boolean,
    default: false
  },
  gameTime: {
    type: Number,
    default: 0
  },
  players: {
    type: Array,
    default: () => []
  },
  currentPlayerId: {
    type: String,
    default: ''
  },
  gameStatus: {
    type: String,
    default: 'waiting'
  }
})

const emit = defineEmits(['paint-action'])

// Canvas相关
const canvasRef = ref(null)
const canvasWidth = 800
const canvasHeight = 600
const ctx = ref(null)
const isDrawing = ref(false)
const lastX = ref(0)
const lastY = ref(0)

// 画笔设置
const currentColor = ref('#FF6B6B')
const brushSize = ref(5)

// 绘图历史
const drawHistory = ref([])
const canUndo = ref(false)

// 触摸事件支持
const isTouchDevice = ref(false)

// 玩家颜色映射
const playerColors = ref(new Map())

onMounted(() => {
  initCanvas()
  isTouchDevice.value = 'ontouchstart' in window
  
  // 监听玩家颜色变化
  watch(() => props.players, (newPlayers) => {
    newPlayers.forEach(player => {
      if (player.color) {
        playerColors.value.set(player.id, player.color)
      }
    })
  }, { immediate: true })
})

onUnmounted(() => {
  // 清理事件监听器
})

function initCanvas() {
  if (canvasRef.value) {
    ctx.value = canvasRef.value.getContext('2d')
    ctx.value.lineCap = 'round'
    ctx.value.lineJoin = 'round'
    updateBrushColor()
    updateBrushSize()
    
    // 设置画布背景
    ctx.value.fillStyle = '#ffffff'
    ctx.value.fillRect(0, 0, canvasWidth, canvasHeight)
    
    // 保存初始状态
    saveDrawHistory()
  }
}

function updateBrushColor() {
  if (ctx.value) {
    ctx.value.strokeStyle = currentColor.value
  }
}

function updateBrushSize() {
  if (ctx.value) {
    ctx.value.lineWidth = brushSize.value
  }
}

function startDrawing(event) {
  if (!props.isGameActive) return
  
  isDrawing.value = true
  const rect = canvasRef.value.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top
  
  lastX.value = x
  lastY.value = y
  
  // 记录开始点
  ctx.value.beginPath()
  ctx.value.moveTo(x, y)
}

function draw(event) {
  if (!isDrawing.value || !props.isGameActive) return
  
  const rect = canvasRef.value.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top
  
  ctx.value.lineTo(x, y)
  ctx.value.stroke()
  
  // 发送绘图动作到后端
  emit('paint-action', {
    type: 'draw',
    x: Math.round(x),
    y: Math.round(y),
    color: currentColor.value,
    size: brushSize.value,
    lastX: Math.round(lastX.value),
    lastY: Math.round(lastY.value)
  })
  
  lastX.value = x
  lastY.value = y
}

function stopDrawing() {
  if (isDrawing.value) {
    isDrawing.value = false
    ctx.value.closePath()
    
    // 保存绘图历史
    saveDrawHistory()
  }
}

// 处理远程玩家的涂色动作
function handleRemotePaintAction(action) {
  if (!ctx.value) return
  
  const playerColor = playerColors.value.get(action.playerId) || action.color || '#000000'
  
  ctx.value.save()
  ctx.value.strokeStyle = playerColor
  ctx.value.lineWidth = action.size || 5
  
  if (action.type === 'draw') {
    ctx.value.beginPath()
    ctx.value.moveTo(action.lastX, action.lastY)
    ctx.value.lineTo(action.x, action.y)
    ctx.value.stroke()
  } else if (action.type === 'clear') {
    clearCanvas()
  }
  
  ctx.value.restore()
  
  // 保存绘图历史
  saveDrawHistory()
}

// 清空画布
function clearCanvas() {
  if (!ctx.value) return
  
  ctx.value.clearRect(0, 0, canvasWidth, canvasHeight)
  ctx.value.fillStyle = '#ffffff'
  ctx.value.fillRect(0, 0, canvasWidth, canvasHeight)
  
  // 发送清空动作
  emit('paint-action', {
    type: 'clear',
    playerId: props.currentPlayerId
  })
  
  saveDrawHistory()
}

// 撤销功能
function undo() {
  if (drawHistory.value.length > 1) {
    drawHistory.value.pop()
    const previousState = drawHistory.value[drawHistory.value.length - 1]
    
    if (previousState) {
      const img = new Image()
      img.onload = () => {
        ctx.value.clearRect(0, 0, canvasWidth, canvasHeight)
        ctx.value.drawImage(img, 0, 0)
      }
      img.src = previousState
    }
    
    canUndo.value = drawHistory.value.length > 1
  }
}

// 保存绘图历史
function saveDrawHistory() {
  if (canvasRef.value) {
    const imageData = canvasRef.value.toDataURL()
    drawHistory.value.push(imageData)
    
    // 限制历史记录长度
    if (drawHistory.value.length > 50) {
      drawHistory.value.shift()
    }
    
    canUndo.value = drawHistory.value.length > 1
  }
}

// 触摸事件处理
function handleTouchStart(event) {
  event.preventDefault()
  if (event.touches.length === 1) {
    const touch = event.touches[0]
    const mouseEvent = new MouseEvent('mousedown', {
      clientX: touch.clientX,
      clientY: touch.clientY
    })
    startDrawing(mouseEvent)
  }
}

function handleTouchMove(event) {
  event.preventDefault()
  if (event.touches.length === 1) {
    const touch = event.touches[0]
    const mouseEvent = new MouseEvent('mousemove', {
      clientX: touch.clientX,
      clientY: touch.clientY
    })
    draw(mouseEvent)
  }
}

function handleTouchEnd(event) {
  event.preventDefault()
  stopDrawing()
}

// 工具函数
function formatTime(seconds) {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

// 暴露方法给父组件
defineExpose({
  clearCanvas,
  handleRemotePaintAction
})
</script>

<style scoped>
.game-canvas-container {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  align-items: center;
}

.canvas-toolbar {
  display: flex;
  gap: 1.5rem;
  align-items: center;
  padding: 1rem;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 0.75rem;
  backdrop-filter: blur(10px);
}

.color-picker,
.brush-size {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: white;
}

.color-input {
  width: 40px;
  height: 30px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.brush-slider {
  width: 100px;
}

.tool-buttons {
  display: flex;
  gap: 0.5rem;
}

.tool-btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 0.5rem;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  cursor: pointer;
  transition: all 0.3s;
}

.tool-btn:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-1px);
}

.tool-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.canvas-wrapper {
  position: relative;
  border-radius: 0.75rem;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.game-canvas {
  display: block;
  border: 2px solid rgba(255, 255, 255, 0.2);
  border-radius: 0.75rem;
  cursor: crosshair;
  background: white;
}

.game-canvas:active {
  cursor: crosshair;
}

.canvas-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  text-align: center;
  border-radius: 0.75rem;
}

.overlay-content h3 {
  margin: 0 0 0.5rem 0;
  font-size: 1.5rem;
}

.overlay-content p {
  margin: 0;
  opacity: 0.8;
}

.game-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  max-width: 800px;
  color: white;
  font-size: 0.875rem;
}

.player-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.player-color {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

@media (max-width: 768px) {
  .canvas-toolbar {
    flex-direction: column;
    gap: 1rem;
  }
  
  .game-canvas {
    width: 100%;
    max-width: 100vw;
  }
  
  .canvas-wrapper {
    width: 100%;
    overflow-x: auto;
  }
}
</style>